import React, {memo, useEffect, useState} from 'react';
import {Redirect} from "react-router-dom";
import {useDispatch, useSelector} from "react-redux";
import request from "../../services/request";
import {message, Upload} from "antd";

import "./index.css";
import {BASE_URL} from "../../services/config";
import {saveRegistered} from "./store/actionCreators";

export default memo(function Register() {
  const dispatch = useDispatch();
  const {registered, isCN} = useSelector(state => ({
    registered: state.registerReducer.registered,
    isCN: state.languageReducer.isCN
  }));
  const [registerKey, setRegisterKey] = useState("");
  const [registerValue, setRegisterValue] = useState("");
  //  上传文件激活电脑
  const softwareConfig = {
    name: 'file',
    showUploadList: false,
    action: `${BASE_URL}/register/uploadLIC`,
    headers: {
      authorization: 'authorization-text'
    },
    onChange(info) {
      if (info.file.status === 'done') {
        request({
          url: "/register/check",
          method: "get"
        }).then(res => {
          switch (res.code) {
            case 200:
              dispatch(saveRegistered(true));
              break;
            case 500:
              message.warn("Instrument inactive");
          }
        }).catch(err => {
          message.warn(err);
        });
        isCN
          ? message.success(`${info.file.name} 加载成功`)
          : message.success(`${info.file.name} file uploaded successfully`);
      } else if (info.file.status === 'error') {
        isCN
          ? message.success(`${info.file.name} 加载失败`)
          : message.error(`${info.file.name} file upload failed.`);
      }
    }
  };
  //  上传文件激活仪器
  const deviceConfig = {
    name: 'file',
    showUploadList: false,
    action: `${BASE_URL}/register/uploadLicense`,
    headers: {
      authorization: 'authorization-text'
    },
    onChange(info) {
      if (info.file.status === 'done') {
        isCN
          ? message.success(`${info.file.name} 加载成功`)
          : message.success(`${info.file.name} file uploaded successfully`);
      } else if (info.file.status === 'error') {
        isCN
          ? message.success(`${info.file.name} 加载失败`)
          : message.error(`${info.file.name} file upload failed.`);
      }
    }
  };

  useEffect(() => {
    request({
      url: "/register/check",
      method: "get"
    }).then(res => {
      switch (res.code) {
        case 200:
          // dispatch(saveRegistered(true));
          break;
        case 500:
          dispatch(saveRegistered(false));
          message.warn("Instrument inactive");
          request({
            url: "/getKey",
            method: "get"
          }).then(res => {
            setRegisterKey(res);
          }).catch(msg => {
            message.warn("Failed to obtain key");
          });
          break;
        default:
          message.warn("error");
          console.log(res);
      }
    }).catch(err => {
      message.warn(err);
    });
  }, []);

  //  输入序列化点击Active激活电脑
  function active() {
    request({
      url: "/reg",
      data: registerValue,
      method: "post"
    }).then(res => {
      if (res === true) {
        dispatch(saveRegistered(true));
      } else {
        message.warn("Activation failed");
      }
    }).catch(err => {
      message.warn(err);
    });
  }

  return registered
    ? <Redirect to="/"/>
    : <section className="register-page">
      <div className="register-language">简体中文</div>
      <div className="register-container">
        <label>
          <span>Key:</span>
          <input type="text" value={registerKey} disabled={true}/>
        </label>
        <label>
          <span>Value:</span>
          <input type="text"
                 value={registerValue}
                 onChange={e => setRegisterValue(e.target.value)}
          />
        </label>
        <div style={{width: 478, minWidth: 478, margin: "5px auto"}}>
          <div className="register-submit"
               onClick={active}
          >Activate
          </div>
          <Upload {...softwareConfig}>
            <div className="register-submit" style={{width: 200, float: "left", margin: "5px 20px"}}>Upload Software LIC</div>
          </Upload>
          <Upload {...deviceConfig}>
            <div className="register-submit" style={{width: 200, float: "left", margin: "5px 15px"}}>Upload Device License</div>
          </Upload>
        </div>
      </div>
    </section>;
});